import axios from 'axios'
import { MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import _message from '@/utils/messageOnce'

const messageOnce = new _message()
// create an axios instance
const service = axios.create({
  // baseURL: '', // + process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: process.env.VUE_APP_IS_PROXY === '1' ? '' : process.env.VUE_APP_BASE_URL, // + process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
  // cookie
  // withCredentials: true
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['token'] = getToken()
      config.headers['AuthorizationToken'] = `Token ${getToken()}`
    }
    // config.headers['Content-type'] = 'application/x-www-form-urlencoded;charset=utf-8'
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      if (res.code === 202052 || res.code === 401) {
        // to re-login
        MessageBox.confirm(res.message,
          '登录超时', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }).catch(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        return
      }
      if (res.code === 4005) {
        return res
      }
      messageOnce.error({
        message: res.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    messageOnce.error({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

// 以下内容为了兼容实操模块
/** post
 * @param options
 * @return {Promise}
 */
export function post(options) {
  return new Promise((resolve, reject) => {
    service(options).then(response => {
      resolve(response)
    })
      .catch(error => {
        reject(error)
      })
  })
}
/** get
 * @param options
 * @return {Promise}
 */
export function get(options) {
  return new Promise((resolve, reject) => {
    service(options).then(response => {
      resolve(response)
    })
      .catch(error => {
        reject(error)
      })
  })
}

/** patch
 * @param options
 * @return {Promise}
 */
export function patch(options) {
  return new Promise((resolve, reject) => {
    service(options).then(response => {
      resolve(response)
    })
      .catch(error => {
        reject(error)
      })
  })
}
/** put
 * @param options
 * @return {Promise}
 */
export function put(options) {
  return new Promise((resolve, reject) => {
    service(options).then(response => {
      resolve(response)
    })
      .catch(error => {
        reject(error)
      })
  })
}
/** delete
 * @param options
 * @return {Promise}
 */
export function deleted(options) {
  console.log('options', options)
  return new Promise((resolve, reject) => {
    service(options).then(response => {
      resolve(response)
    })
      .catch(error => {
        reject(error)
      })
  })
}
